<template>
	<div class="station-map-container">
		<!-- A. 数据汇总 -->
		<a-form ref="searchFormRef" class="search-form base-mb15" :model="searchFormState" @finish="onSearchFinish">
			<a-row :gutter="[10, 24]" align="middle">
				<!-- 1. 运营商 -->
				<a-col :xs="24" :sm="12" :md="6">
					<a-form-item name="orgId" :label="$t('self.businessStation.tips8')"
						:label-col="{ style: { minWidth: '70px' } }">
						<a-select allow-clear v-model:value="searchFormState.orgId" :options="searchOrgOptions"
							@change="handleOrgChange" :field-names="{ label: 'orgName', value: 'id' }"
							:placeholder="$t('self.pleaseChoose')" />
					</a-form-item>
				</a-col>
				<!-- 2. 站点 -->
				<a-col :xs="24" :sm="12" :md="6">
					<a-form-item name="stationId" :label="$t('self.businessStation.tips1')"
						:label-col="{ style: { minWidth: '70px' } }">
						<a-select allow-clear v-model:value="searchFormState.stationId" :options="stationOptions"
							@change="handleStationNameChange" :field-names="{ label: 'stationName', value: 'id' }"
							:placeholder="$t('self.pleaseChoose')" />
					</a-form-item>
				</a-col>
				<!-- 3. 按钮组 -->
				<a-col :xs="24" :sm="24" :md="6" style="display: flex; align-items: center; gap: 8px;">
					<a-form-item style="margin: 0;">
						<a-button type="primary" html-type="submit" @click="loadData"> {{ $t('self.searchButton') }}
						</a-button>
					</a-form-item>
					<a-form-item style="margin: 0;">
						<a-button @click="resetSearchForm">{{ $t('self.resetButton') }}</a-button>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<div class="data-summary-section">
			<a-row :gutter="16">
				<!-- 第一行 -->
				<a-col :span="6">
					<a-card class="summary-card bg1 jump-to-detail"  @click="handleJumpToDetail(1,7001)">
						<div class="card-title">{{ $t('self.order.tips203') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.chargingPower.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.chargingPower.today }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.chargingPower.motoKwh }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.chargingPower.carKwh }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>

				<a-col :span="6">
					<a-card class="summary-card bg2 jump-to-detail"  @click="handleJumpToDetail(1,7001)">
						<div class="card-title">{{ $t('self.stationMap.tips1a') }}{{ $t('self.order.tips220') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.chargingAmount.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.chargingAmount.today }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.chargingAmount.motoMoney }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.chargingAmount.carMoney }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>

				<a-col :span="6">
					<a-card class="summary-card bg3 jump-to-detail"  @click="handleJumpToDetail(1,7001)">
						<div class="card-title">{{ $t('self.stationMap.tips15a') }}{{ $t('self.stationMap.tips17') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.ChargingTime.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.ChargingTime.today }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.ChargingTime.motoTime }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.ChargingTime.carTime }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card class="summary-card bg4 jump-to-detail"  @click="handleJumpToDetail(1,7001)">
						<div class="card-title">{{ $t('self.stationMap.tips2a') }}{{ $t('self.stationMap.tips16') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.chargingCount.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.chargingCount.today }}</span>
							</div>
							<!-- ??? -->
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.motoCharging }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.carCharging }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
			</a-row>

			<a-row :gutter="16" style="margin-top: 16px;">
				<!-- 第二行 -->
				<a-col :span="6">
					<a-card class="summary-card bg5 jump-to-detail"  @click="handleJumpToDetail(2,1003)">
						<div class="card-title">{{ $t('self.stationMap.tips57') }}(%)</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.serveceMoney.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.serveceMoney.today }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.serveceMoney.moneyMotoService }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.serveceMoney.moneyCarService }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>

				<a-col :span="6">
					<a-card class="summary-card bg6 jump-to-detail"  @click="handleJumpToDetail(3,2003)">
						<div class="card-title">{{ $t('self.stationMap.tips25a') }}{{ $t('self.order.tips220') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.tips28') }}:</span>
								<span class="data-value">{{ summaryData.RfidMoney.total + summaryData.RfidMoney.today}}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.tips29') }}:</span>
								<span class="data-value">{{ summaryData.RfidMoney.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.tips32') }}:</span>
								<span class="data-value">{{ summaryData.RfidMoney.today }}</span>
							</div>
							<div class="data-item" style="margin-top: 30px;">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card class="summary-card bg7 jump-to-detail"  @click="handleJumpToDetail(4,4001)">
						<div class="card-title">{{ $t('self.stationMap.tips31a') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.tips28') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.motoCharging + summaryData.pileInfo.carCharging}} </span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.motoCharging }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.carCharging }}</span>
							</div>
							<div class="data-item"  style="margin-top: 30px;">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>

				<a-col :span="6">
					<a-card class="summary-card bg8 jump-to-detail"  @click="handleJumpToDetail(5,1002)">
						<div class="card-title">{{ $t('self.stationMap.tips35a') }}{{ $t('self.stationMap.tips16') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.tips23') }}:</span>
								<span class="data-value">{{ summaryData.gunInfo.normal }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.tips24') }}:</span>
								<span class="data-value">{{ summaryData.gunInfo.fault }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.tips67') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.offLineMoto }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.tips66') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.offLineCar }}</span>
							</div>

							<div class="data-item"  style="margin-top: 55px;">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
			</a-row>
			<!-- 第3行 -->
			<a-row :gutter="16" style="margin-top: 16px;">
				<a-col :span="6">
					<a-card class="summary-card bg9 jump-to-detail"  @click="handleJumpToDetail(6,2001)">
						<div class="card-title">{{ $t('self.stationMap.tips12a') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.orgInfo.allUser }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.orgInfo.todyUser }}</span>
							</div>
							<!-- <div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.motoCharging }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.carCharging }}</span>
							</div> -->
							<div class="data-item"  style="margin-top: 55px;">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card class="summary-card bg10 jump-to-detail"  @click="handleJumpToDetail(5,1002)">
						<div class="card-title">{{ $t('self.stationMap.tips3a') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.stationCount.total }}</span>
							</div>
							<!--  后台接口没有返回 todo-->
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.orgInfo.todyUser }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.stationCount.moto }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.stationCount.car }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>


				<a-col :span="6">
					<a-card class="summary-card bg11 jump-to-detail"  @click="handleJumpToDetail(1)">
						<div class="card-title">{{ $t('self.stationMap.tips4a') }}</div>
						<div class="card-content">

							<!--  -->
							<!-- <div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.stationCount.total }}</span>
							</div> -->


							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.pileAll }}</span>
							</div>

							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.onLineMoto }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.onLineCar }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card class="summary-card bg12 jump-to-detail"  @click="handleJumpToDetail(5,1002)">
						<div class="card-title">{{ $t('self.stationMap.tips5a') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessCharging.states.tips1') }}:</span>
								<span class="data-value">{{ summaryData.gunInfo.offLine }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessCharging.states.tips4') }}:</span>
								<span class="data-value">{{ summaryData.gunInfo.free }}</span>
							</div>

							<div class="data-item">
								<span class="data-label">{{ $t('self.businessCharging.states.tips11') }}:</span>
								<span class="data-value">{{ summaryData.gunInfo.charginMoto }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessCharging.states.tips12') }}:</span>
								<span class="data-value">{{ summaryData.gunInfo.charginCar }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>


						</div>
					</a-card>
				</a-col>
			</a-row>

			<!-- 第四行 -->
			<a-row :gutter="16" style="margin-top: 16px;">
				<a-col :span="6">
					<a-card class="summary-card bg13 jump-to-detail"  @click="handleJumpToDetail(5,1002)">
						<div class="card-title">{{ $t('self.stationMap.tips27a') }}</div>
						<div class="card-content">
							<!--  -->
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.stationCount.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.pileInfo.pileAll }}</span>
							</div>




							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.EMotorcycle }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.ECar }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card class="summary-card bg14 jump-to-detail"  @click="handleJumpToDetail(2,1001)">
						<div class="card-title">{{ $t('self.stationMap.tips26a') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.orgInfo.allOrg }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.orgInfo.todyOrg }}</span>
							</div>


							<!--  -->
							<!-- <div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.EMotorcycle }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.ECar }}</span>
							</div> -->
							<div class="data-item" style="margin-top: 55px;">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card class="summary-card bg15 jump-to-detail"  @click="handleJumpToDetail(2,1001)">
						<div class="card-title">{{ $t('self.stationMap.tips33a') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.orgInfo.countryOrg }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.orgInfo.countryOrgTody }}</span>
							</div>

							<div class="data-item" style="margin-top: 55px;">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>

				<a-col :span="6">
					<a-card class="summary-card bg16 jump-to-detail"  @click="handleJumpToDetail(7,3)">
						<div class="card-title">{{ $t('self.stationMap.tips34a') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.orgInfo.agent }}</span>
							</div>
							<!-- <div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.orgInfo.agentTody }}</span>
							</div> -->

							<!--  -->
							<!-- <div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.EMotorcycle }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.ECar }}</span>
							</div> -->
							<div class="data-item"  style="margin-top: 85px;">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
			</a-row>
			<!-- 第5行 -->
			<!-- jian feng ping gu -->
			<a-row :gutter="16" style="margin-top: 16px;">
				<a-col :span="6">
					<a-card class="summary-card bg17 jump-to-detail"  @click="handleJumpToDetail(1,7001)">
						<div class="card-title">{{ $t('self.stationMap.tips61') }}{{ $t('self.order.tips221') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.chargingPower.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.chargingPower.today }}</span>
							</div>

							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.sumTimeKwh.maxMoto }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.sumTimeKwh.maxCar }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>

				<a-col :span="6">
					<a-card class="summary-card bg18 jump-to-detail"  @click="handleJumpToDetail(1,7001)">
						<div class="card-title">{{ $t('self.stationMap.tips62') }}{{ $t('self.order.tips221') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.chargingAmount.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.chargingAmount.today }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.sumTimeKwh.heightMoto }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.sumTimeKwh.heightCar }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>

				<a-col :span="6">
					<a-card class="summary-card bg19 jump-to-detail"  @click="handleJumpToDetail(1,7001)">
						<div class="card-title">{{ $t('self.stationMap.tips63') }}{{ $t('self.order.tips221') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.ChargingTime.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.ChargingTime.today }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.sumTimeKwh.avgMoto }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.sumTimeKwh.avgCar }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
				<a-col :span="6">
					<a-card class="summary-card bg20 jump-to-detail"  @click="handleJumpToDetail(1,7001)">
						<div class="card-title">{{ $t('self.stationMap.tips64') }}{{ $t('self.order.tips221') }}</div>
						<div class="card-content">
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.total') }}:</span>
								<span class="data-value">{{ summaryData.chargingCount.total }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.stationMap.today') }}:</span>
								<span class="data-value">{{ summaryData.chargingCount.today }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips1') }}:</span>
								<span class="data-value">{{ summaryData.sumTimeKwh.aslowMoto }}</span>
							</div>
							<div class="data-item">
								<span class="data-label">{{ $t('self.businessStation.vehicleType.tips2') }}:</span>
								<span class="data-value">{{ summaryData.sumTimeKwh.aslowCar }}</span>
							</div>
							<div class="data-item">
								<span class="data-label"></span>
								<span class="data-label">{{ $t('self.stationMap.tips65') }}</span>
							</div>
						</div>
					</a-card>
				</a-col>
			</a-row>
		</div>



		<!-- C. 代理充值记录 -->
		<!-- <div class="list">
			<a-card :title="$t('self.stationMap.tips22')">
				<s-table ref="stableRef" :data="tableData" :columns="sourceColumn" row-key="id"
					:light-index="tableConfig.lightIndex" :is-row-selection="false" :is-show-tool="false"
					:scroll="{ x: 1400 }">
					<template #bodyCell="{ column, record, index }">
						<template v-if="column.key === 'type' && record">
							{{ getSourceTypeTxt(record.type) }}
						</template>
					</template>
				</s-table>
			</a-card>
		</div> -->
		<!-- D. 数据统计图表 -->
		<div class="chart-section">
			<a-row :gutter="16">
				<!-- 左侧保持原有柱状图 -->
				<a-col :xs="24" :sm="24" :md="16"> 
					<a-card>
						<!-- 单选按钮 + 日期选择器 同一行 -->
						<a-row :gutter="[8, 8]" align="middle">
							<!-- 1. 单选按钮组 -->
							<a-col :xs="24" :sm="24" :md="10" :lg="10" :xl="10">
								<a-radio-group v-model:value="dateMode" @change="handleChartTypeChange(1)">
									<a-radio-button value="year">{{ radioTxt.year  }}</a-radio-button>
									<a-radio-button value="month">{{ radioTxt.month }}</a-radio-button>
									<a-radio-button value="week">{{ radioTxt.week  }}</a-radio-button>
									<a-radio-button value="day">{{ radioTxt.day   }}</a-radio-button>
								</a-radio-group>
							</a-col>

							<a-col :xs="24" :sm="24" :md="11" :lg="11" :xl="11"  style="display: flex; justify-content: flex-start;">
								<!-- 动态区间组件 -->
								<a-range-picker
									:picker="pickerType"
									v-model:value="rangeValue"
									:allowClear="true"
									:placeholder="rangePlaceholder"
									style="width:100%;max-width:320px"
									@change="onRangeChange"
								/>
							</a-col>

							<!-- 2. 下载按钮 -->
							<a-col :xs="24" :sm="24" :md="3" :lg="3" :xl="3">
								<a-dropdown 
									:trigger="['click']" 
									:getPopupContainer="(node) => node"
									overlayClassName="chart-download-dropdown">
									<template #overlay>
										<a-menu @click="handleDownload">
											<a-menu-item key="print">
												<printer-outlined />
												<span style="padding-left: 8px;font-size: 15px;">Print Chart</span>
											</a-menu-item>
											<a-menu-item key="svg">
												<download-outlined />
												<span style="padding-left: 8px;font-size: 15px;">Download SVG</span>
											</a-menu-item>
											<a-menu-item key="pdf">
												<download-outlined />
												<span style="padding-left: 8px;font-size: 15px;">Download PDF</span>
											</a-menu-item>
											<a-menu-item key="excel">
												<download-outlined />
												<span style="padding-left: 8px;font-size: 15px;">Download Excel</span>
											</a-menu-item>
											<a-menu-item key="csv">
												<download-outlined />
												<span style="padding-left: 8px;font-size: 15px;">Download CSV</span>
											</a-menu-item>
											<a-menu-item key="jpeg">
												<download-outlined />
												<span style="padding-left: 8px;font-size: 15px;">Download JPEG</span>
											</a-menu-item>
										</a-menu>
									</template>
									<div class="bnt">
										<!-- <a-button :icon="DownloadOutlined" size="small" style="margin-left: 8px;"> -->
											Download
										<!-- </a-button> -->
									</div>
								</a-dropdown>
							</a-col>

						</a-row>

						<!-- 图表类型切换 -->
						<template #title>
							<div class="indicator-scroll-wrapper">
								<a-radio-group
								v-model:value="chartType"
								@change="handleChartTypeChangeZ"
								class="indicator-radio-group">
								<a-radio-button value="totalCharge">
									{{ $t('self.stationMap.tips14') }}
								</a-radio-button>
								<a-radio-button value="totalChargeMoney">
									{{ $t('self.stationMap.tips1') }}
								</a-radio-button>
								<a-radio-button value="totalChargeCount">
									{{ $t('self.stationMap.tips2') }}
								</a-radio-button>
								<a-radio-button value="totalChargeTime">
									{{ $t('self.stationMap.tips15') }}
								</a-radio-button>
								<a-radio-button value="totalServeceMoney">
									{{ $t('self.stationMap.tips47') }}
								</a-radio-button>
								<a-radio-button value="Wallet">
									{{ $t('self.stationMap.tips48') }}
								</a-radio-button>
								</a-radio-group>
							</div>
						</template>

						<div class="chart-container1" style="width:100%;height:514px;">
							<div ref="chartRef" style="width:100%;height:514px;"></div>
						</div>
					</a-card>
				</a-col>
				<!-- 右侧新增饼图 -->
				<a-col a-col :xs="24" :sm="24" :md="8">
					<a-card :title="$t('self.order.tips60')"> 
						<div ref="pieRef" style="width:100%;height:544px;"></div>
					</a-card>
				</a-col>
			</a-row>

			<!--  第二行饼图-->
			<a-row :gutter="24"  class="chart-row">
				<a-col a-col :xs="24" :sm="24" :md="12">
					<a-card :title="$t('self.stationMap.tips27')"  style="width: 100%;margin:0 auto;"> 
						<div ref="pieRef1" style="width:100%;height:380px;"></div>
					</a-card>
				</a-col>
				<a-col a-col :xs="24" :sm="24" :md="12" class="pie-col">
					<a-card :title="$t('self.stationMap.tips31')" style="width: 100%;margin:0 auto;"> 
						<div ref="pieRef2" style="width:100%;height:380px;"></div>
					</a-card>
				</a-col>
			</a-row>

			<!--  第3行饼图-->
			<a-row :gutter="24" style="margin-top: 20px;margin-bottom: 20px;display:flex;">
				<a-col a-col :xs="24" :sm="24" :md="12" >
					<a-card :title="$t('self.stationMap.tips36')" style="width: 100%;margin:0 auto;"> 
						<a-row><a-col :xs="24" :sm="24" :md="11" :lg="11" :xl="11"><div style="height:50px;width:100%;"></div></a-col></a-row>
						<div ref="pieRef3" style="width:100%;height:380px;"></div>
					</a-card>
				</a-col>
				<a-col a-col :xs="24" :sm="24" :md="12" >
					<a-card :title="$t('self.stationMap.tips37')"> 
						<a-row :gutter="[8, 8]" align="middle" justify="space-between" >
							<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<a-radio-group v-model:value="dateMode1" @change="handleChartTypeChange(3)" 
								style="display: flex;flex-direction: row;margin-bottom: 10px;width:100%;">
									<a-radio-button value="year">{{ radioTxt.year  }}</a-radio-button>
									<a-radio-button value="month">{{ radioTxt.month }}</a-radio-button>
									<a-radio-button value="week">{{ radioTxt.week  }}</a-radio-button>
									<a-radio-button value="day">{{ radioTxt.day   }}</a-radio-button>
								</a-radio-group>
							</a-col>
							<!-- <a-col :xs="24" :sm="24" :md="11" :lg="11" :xl="11">
								<a-radio-group v-model:value="carMode" @change="handleChartTypeChange(3)" style="display: flex;justify-content: flex-end;flex-direction: row;margin-bottom: 10px;">
									<a-radio-button value="moto">{{ $t('self.stationMap.tips45') }}</a-radio-button>
									<a-radio-button value="car">{{ $t('self.stationMap.tips46') }}</a-radio-button>
								</a-radio-group>
							</a-col> -->
						</a-row>
						<div ref="pieRef4" style="width:100%;height:388px;"></div>
					</a-card>
				</a-col>
			</a-row>
		</div>

		<!-- B. Google地图 -->
		<div class="map-section">
			<a-card :title="$t('self.stationMap.tips13')">

				<div id="google-map" class="google-map-container" style="margin-bottom:20px"></div>

				<!-- 新增5个下拉选择框 -->
				<a-form ref="mapSearchFormRef" class="search-form base-mb15" :model="mapSearchFormState" @finish="onMapSearchFinish">
					<a-row :gutter="[10, 24]" align="middle">
						<!-- 1. 非洲所有国家下拉 -->
						<a-col :xs="24" :sm="4" :md="4">
						<a-form-item name="africaCountry"
							:label-col="{ style: { minWidth: '100px' } }">
							<a-select allow-clear v-model:value="mapSearchFormState.africaCountry" 
							:options="africaCountryOptions"   :field-names="{ label: 'display', value: 'value' }"  @change="handleAfricaCountryChange"
							:placeholder="$t('self.pleaseChoose')">
							</a-select>
						</a-form-item>
						</a-col>

						<!-- 2. 非洲所有测试下拉（假设“测试”指测试项目/类型） -->
						<a-col :xs="24" :sm="4" :md="4">
						<a-form-item name="africaTestType"
							:label-col="{ style: { minWidth: '100px' } }">
							<a-select allow-clear v-model:value="mapSearchFormState.africaTestType" 
							:options="africaTestTypeOptions"
  							:field-names="{ label: 'label', value: 'value' }" @change="handleAfricaTestTypeChange"
							:placeholder="$t('self.pleaseChoose')">
							</a-select>
						</a-form-item>
						</a-col>

						<!-- 3. 车辆类型下拉（E-CAR、E-摩托车） -->
						<a-col :xs="24" :sm="4" :md="4">
						<a-form-item name="vehicleType"
							:label-col="{ style: { minWidth: '100px' } }">
							<a-select allow-clear v-model:value="mapSearchFormState.vehicleType" 
							:options="vehicleTypeOptions" @change="handleVehicleTypeChange"
							:placeholder="$t('self.pleaseChoose')">
							</a-select>
						</a-form-item>
						</a-col>

						<!-- 4. 充电桩容量下拉（120kw、70kw、7kw） -->
						<a-col :xs="24" :sm="4" :md="4">
						<a-form-item name="pileCapacity"
							:label-col="{ style: { minWidth: '100px' } }">
							<a-select allow-clear v-model:value="mapSearchFormState.pileCapacity" 
							:options="pileCapacityOptions" @change="handlePileCapacityChange"
							:placeholder="$t('self.pleaseChoose')">
							</a-select>
						</a-form-item>
						</a-col>

						<!-- 5. 充电桩状态下拉（充电中、空闲、故障） -->
						<a-col :xs="24" :sm="4" :md="4">
						<a-form-item name="pileStatus"
							:label-col="{ style: { minWidth: '100px' } }">
							<a-select allow-clear v-model:value="mapSearchFormState.pileStatus" 
							:options="pileStatusOptions" @change="handlePileStatusChange"
							:placeholder="$t('self.pleaseChoose')">
							</a-select>
						</a-form-item>
						</a-col>

						<!-- 表单提交按钮 -->
						<a-col :xs="24" :sm="4" :md="4" style="display: flex; align-items: center; gap: 8px;margin-left: 10px;">
							<a-form-item style="margin: 0;">
								<a-button type="primary" html-type="submit">{{ $t('self.searchButton') }}</a-button>
							</a-form-item>
							<a-form-item style="margin: 0;">
								<a-button @click="resetMapSearchForm">{{ $t('self.resetButton') }}</a-button>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</a-card>
		</div>

		<!-- C. 充电记录 -->
		<div class="list">
			
			<a-card :title="$t('self.stationMap.tips38')">
				<a-form
					ref="searchFormRefHis"
					class="search-form base-mb15"
					:label-col="{ style: { minWidth: '100px' } }"
					:model="searchFormStateHis"
					@finish="onSearchFinishHis"
    			>
			<a-row :gutter="[10, 24]">
				<a-col :span="6">
				<a-form-item name="userName" label="Customer Name">
					<a-input v-model:value="searchFormStateHis.userName"></a-input>
				</a-form-item>
				</a-col>

				<a-col :span="6">
				<a-form-item name="mobile" :label="$t('self.order.tips2')">
					<a-input v-model:value="searchFormStateHis.mobile"></a-input>
				</a-form-item>
				</a-col>
				<a-col :span="6">
				<a-form-item name="orderNo" :label="$t('self.order.tips13')">
					<a-input v-model:value="searchFormStateHis.orderNo"></a-input>
				</a-form-item>
				</a-col>
				<a-col :span="6">
				<a-form-item name="orgId" :label="$t('self.order.tips12')">
					<a-select v-model:value="searchFormStateHis.orgId" :options="searchOrgOptionsHis" :fieldNames="{label: 'orgName',value: 'id'}" :placeholder="$t('self.pleaseChoose')"/>
				</a-form-item>
				</a-col>

				<a-col :span="6">
				<a-form-item name="vehicle" :label="$t('self.stationMap.vehicleType')">
					<a-select v-model:value="searchFormStateHis.vehicle" :options="vehicleTypeOptionsHis" :fieldNames="{label: 'label',value: 'value'}" :placeholder="$t('self.pleaseChoose')"/>
				</a-form-item>
				</a-col>
				<a-col :span="6">
				<a-form-item name="gunType" label="ChargeType">
					<a-select v-model:value="searchFormStateHis.gunType" :options="chargeTypeOptions" :fieldNames="{label: 'label',value: 'value'}" :placeholder="$t('self.pleaseChoose')"/>
				</a-form-item>
				</a-col>
				<a-col :span="6">
				<a-form-item name="startTime" :label="$t('self.order.tips14')">
					<a-date-picker v-model:value="searchFormStateHis.startTime" style="width: 100%;"/>
				</a-form-item>
				</a-col>
				<a-col :span="6">
				<a-form-item name="endTime" :label="$t('self.order.tips15')">
					<a-date-picker v-model:value="searchFormStateHis.endTime" style="width: 100%;"/>
				</a-form-item>
				</a-col>
				<a-col :span="6" offset="1" class="base-flex base-rows">
				<a-button type="primary" html-type="submit"  @click="loadDataHis">{{ $t('self.searchButton') }}</a-button>
				<a-button class="base-ml10" @click="resetSearchFormHis">{{ $t('self.resetButton') }}</a-button>
				</a-col>
			</a-row>
			</a-form>
				<s-table 
					ref="stableRefHis" 
					:columns="sourceColumnHis" 
					row-key="id" 
					:is-row-selection="false" 
					@selectionChange="tableSelectionChangeHis" 
					:pagination="paginationHis"
					:api-obj="apiObjHis"
					:api-method="'POST'"
					:params="tableParams"
					:is-show-tool="false" 
					:scroll="{ x: 2500 }">
				</s-table>
			</a-card>
		</div>
	</div>
</template>

<script setup>
	import {
		Loader
	} from '@googlemaps/js-api-loader'
	import {
		getCurrentInstance,
		nextTick,
		ref,
		reactive,
		onMounted,
		watch,
		computed,
		onUnmounted
	} from 'vue'
	import {
		useRoute,
		useRouter
	} from 'vue-router'

	import { mainStore } from '@/stores/mainStore'
	import { userStore } from '@/stores/userStore'

	import * as echarts from 'echarts'
	import {
		message
	} from 'ant-design-vue'
	import * as XLSX from 'xlsx'; 
	import { DownloadOutlined, PrinterOutlined } from '@ant-design/icons-vue'; 
	import cityData from '@/config/data.js'
	import dayjs from 'dayjs'
	const cityRaw =  cityData.cityRaw
	const sourcePagination = ref({
		total: 0,
		current: 1,
		pageSize: 10
	})
	const {
		proxy
	} = getCurrentInstance()
	const $TOOL = proxy.$TOOL
	const $API = proxy.$API
	const $T = proxy.$t
	const route = useRoute()
	const router = useRouter()
	const mainStoreInstance = mainStore();
	const userStoreInstance = userStore(); 
	const radioTxt = computed(() => ({
		all: proxy.$t('self.index.tips5'),
		year: proxy.$t('self.index.tips1'),
		month: proxy.$t('self.index.tips2'),
		week: proxy.$t('self.index.tips3'),
		day: proxy.$t('self.index.tips4')
	}))
	const stationOptions = ref([])
	const searchFormRef = ref(null)
	const searchFormState = ref({
		orgId: null,
		stationId: null
	})


	const searchOrgOptions = ref([])

	// 汇总数据
	const summaryData = reactive({
		chargingPower: {
			total: 0,
			today: 0,
			motoKwh: 0,
			carKwh: 0,
		},
		chargingAmount: {
			total: 0,
			today: 0,
			motoMoney:0,
			carMoney:0
		},
		chargingCount: {
			total: 0,
			today: 0
		},
		ChargingTime: {
			total: 0,
			today: 0,
			motoTime: 0,
			carTime: 0
		},
		stationCount: {
			total: 0,
			today: 0,
			moto: 0,
			car: 0,
			areaData: 0
		},
		pileInfo: {
			pileAll: 0,
			stationAll: 0,
			motoCharging: 0,
			carCharging: 0,
			onLineMoto:0,
			onLineCar:0,
			offLineCar: 0,
			offLineMoto: 0,
			pileChargingAll: 0//充电中的桩
		},
		sumTimeKwh: {
			avg: 0,
			max: 0,
			aslow:0,
			height:0,
			avgMoto:0,
			maxMoto:0,
			highYMoto:0,
			aslowMoto:0,
			heightMoto:0,
			avgCar:0,
			maxCar:0,
			aslowCar:0,
			heightCar:0
		},
		serveceMoney: {
			total: 0,
			today: 0,
			moneyMotoService: 0,
			moneyCarService: 0
		},
		gunInfo: {
			total: 0,
			offLine: 0,
			wait: 0,
			occupy: 0,//充电中
			fault: 0,
			normal: 0,
			free: 0,
			charginMoto: 0,
			charginCar: 0,

		},
		// orgInfo运营商详情累计：allOrg
		// 运营商详情今天累计：todyUser
		// 国家代理累计： countryOrg
		// 国家代理今天累计： countryOrgTody
		orgInfo: {
			allOrg: 0,
			todyOrg:0,
			allUser:0,
			todyUser: 0,
			countryOrg: 0,
			countryOrgTody: 0,
			agent:0,
			agentTody:0
		},		
		RfidMoney: {
			total: 0,//钱包已使用金额
			today: 0//钱包未使用金额
		},
		EMotorcycle:0,
		ECar:0,
		CarTypeAll:0,
		motoMoney:0,
		carMoney:0
	})

	// 地图相关
	let map = null
	const mapInstance = ref(null)
	const markers = ref([])

	// 获取汇总数据
	const querySum = async (type) => {
		try {
			$API.backend.index.indexQuerySum.post({
				orgId: formState.value.orgIds,
				stationId: formState.value.chargeStationIds,
				type:type ? type : 4
			}).then(res => {
				const {
					objData
				} = res

				summaryData.chargingPower.total = objData.totalCharge || 0
				summaryData.chargingPower.today = objData.todayTotalCharge || 0
				summaryData.chargingPower.motoKwh = objData.motoKwh || 0
				summaryData.chargingPower.carKwh = objData.carKwh || 0

				summaryData.chargingCount.total = objData.totalChargeCount || 0
				summaryData.chargingCount.today = objData.todayTotalChargeCount || 0

				summaryData.chargingAmount.total = objData.totalChargeMoney || 0
				summaryData.chargingAmount.today = objData.todayTotalChargeMoney || 0
				summaryData.chargingAmount.motoMoney = objData.motoMoney || 0
				summaryData.chargingAmount.carMoney = objData.carMoney || 0

				summaryData.ChargingTime.total = objData.totalChargeTime || 0
				summaryData.ChargingTime.today = objData.todayTotalChargeTime || 0
				summaryData.ChargingTime.motoTime = objData.motoTime || 0
				summaryData.ChargingTime.carTime = objData.carTime || 0

				summaryData.serveceMoney.total = objData.totalServeceMoney || 0
				summaryData.serveceMoney.today = objData.totalServeceMoneyTody || 0
				summaryData.serveceMoney.moneyMotoService = objData.moneyMotoService || 0
				summaryData.serveceMoney.moneyCarService = objData.moneyCarService || 0

				summaryData.RfidMoney.total = objData.totalRfidMoney || 0
				summaryData.RfidMoney.today = objData.totalChargeMoney || 0

				
				summaryData.EMotorcycle = objData.motoNum|| 0
				summaryData.ECar = objData.carNum  || 0
				summaryData.CarTypeAll =  summaryData.EMotorcycle + summaryData.ECar

				summaryData.motoMoney= objData.motoMoney || 0
				summaryData.carMoney = objData.carMoney || 0

				updatePie4()

			}).catch(err => {
				console.log(err)
			})
		} catch (error) {
			message.error(err.msg);
		}
	}

	const queryChargeGunCount = async () => {
		try {
			$API.backend.index.ChargeGunCount.post({
				orgId: formState.value.orgIds,
				stationId: formState.value.chargeStationIds,
			}).then(res => {
				const {
					objData
				} = res
				summaryData.gunInfo.total = objData.gunAll
				//{"code":200,"msg":"success","objData":{"offLine":离线,"wait":null,"occupy":充电中,"gunAll":0,"alarm":null,"fault":故障,"appointment":null,"free":空闲,"complete":null，normal：正常}}
				// 故障以及连接状态：
				// "fault":故障
				// normal：正常
				summaryData.gunInfo.total = objData.gunAll || 0
				summaryData.gunInfo.offLine = objData.offLine || 0
				summaryData.gunInfo.wait = objData.wait || 0
				summaryData.gunInfo.occupy = objData.occupy || 0

				summaryData.gunInfo.fault = objData.fault || 0
				summaryData.gunInfo.normal = objData.normal || 0
				summaryData.gunInfo.free = objData.free || 0

				summaryData.gunInfo.charginMoto = objData.charginMoto || 0
				summaryData.gunInfo.charginCar = objData.charginCar || 0
			}).catch(err => {
				console.log(err)
			})
		} catch (error) {
			message.error($T('self.message.loadFailed'))
		}
	}
	const queryChargePileCount = async () => {
		try {
			$API.backend.index.ChargePileCount.post({
				orgId: formState.value.orgIds,
				stationId: formState.value.chargeStationIds,
			}).then(res => {
				const {
					objData
				} = res
				summaryData.pileInfo.pileAll = objData.pileAll || 0

				summaryData.pileInfo.stationAll = objData.stationAll || 0
				summaryData.pileInfo.motoCharging = objData.motoCharging || 0
				summaryData.pileInfo.carCharging = objData.carCharging || 0
				summaryData.pileInfo.onLineMoto = objData.onLineMoto || 0
				summaryData.pileInfo.onLineCar = objData.onLineCar || 0
				summaryData.pileInfo.offLineCar = objData.offLineCar || 0
				summaryData.pileInfo.offLineMoto = objData.offLineMoto || 0
				summaryData.pileInfo.pileChargingAll = objData.pileChargingAll || 0//充电中的桩

			}).catch(err => {
				console.log(err)
			})
		} catch (error) {
			message.error($T('self.message.loadFailed'))
		}
	}
	const queryAllStationCount = async () => {
		try {
			$API.backend.index.AllStationCount.post({
				orgId: formState.value.orgIds,
				stationId: formState.value.chargeStationIds,
			}).then(res => {
				const {
					objData
				} = res
				console.log("queryAllStationCount===", objData[0].top5,objData[0].number)
				summaryData.stationCount.total = objData[0].number || 0
				summaryData.areaData = objData[0].top5 || [];
				//todo
				//stationCount.moto
				//stationCount.car
				updatePie3();
			}).catch(err => {
				console.log(err)
			})
		} catch (error) {
			message.error($T('self.message.loadFailed'))
		}
	}
	const AddUserOrg = async () => {
		try {
			$API.backend.index.queryAddUserOrg.post({
				orgId: formState.value.orgIds,
				stationId: formState.value.chargeStationIds,
			}).then(res => {
				const {
					objData
				} = res
				summaryData.orgInfo.allUser = res.objData.objData.allUser || 0
				summaryData.orgInfo.todyUser = res.objData.objData.todyUser || 0

				summaryData.orgInfo.allOrg = objData.objData.allOrg
				summaryData.orgInfo.todyOrg = objData.objData.todyOrg || 0
				summaryData.orgInfo.countryOrg = objData.objData.countryOrg || 0
				summaryData.orgInfo.countryOrgTody = objData.objData.countryOrgTody || 0

				summaryData.orgInfo.agent = objData.objData.agent || 0
				summaryData.orgInfo.agentTody = objData.objData.agentTody || 0
			}).catch(err => {
				console.log(err)
			})
		} catch (error) {
			message.error($T('self.message.loadFailed'))
		}
	}
	const onSearchFinish = (values) => {
		stableRef.value.upData(values, 1)
	}
	// 重置搜索表单
	const resetSearchForm = () => {
		searchFormRef.value.resetFields()
	}
	//获取当前登录用户的所属运营商
	const formState = ref({
		"id": $TOOL.data.get('USERID'),
		"step": 1,
		"orgIds": [],
		"chargeStationIds": [],
		"beginDate": null,
		"endDate": null
	})
	//运营商筛选
	const getUserOrgRole = () => {
		$API.backend.systemUser.queryUserOrgRole.post({
			id: formState.value.id
		}).then(res => {
			const {
				objData
			} = res
			searchOrgOptions.value = objData.orgList
			searchOrgOptionsHis.value = objData.orgList
		}).catch(err => {
			console.log(err)
		})
	}
	//站点筛选
	const handleStationNameChange = (stationId) => {
		formState.value.chargeStationIds = stationId
	}

	//代理收费记录
	const getAgentChargeRecords = async () => {
		try {
			stableRef.value?.setLoading?.(true)
			const res = await $API.backend.index.agentChargeRecords.post()
			if (res.code === 200) {
				tableData.value = res.objData
			}
		} catch (e) {
			message.error($T('self.message.loadFailed'))
		} finally {
			stableRef.value?.setLoading?.(false)
		}
	}
	const selectedKey = ref([])
	const stableRef = ref(null)
	const tableData = ref([])
	const tableConfig = ref({
		apiObj: null,
		dataPath: '',
		totalPath: '',
		lightIndex: []
	})
	// 表格列
	const sourceColumn = ref([])
	sourceColumn.value = [{
			title: $T('self.userCharge.tips21'),
			dataIndex: 'cardNo',
			key: 'cardNo'
		},
		{
			title: $T('self.userCharge.tips3'),
			dataIndex: 'userName',
			key: 'userName',
			// 自定义显示列
			customRender: ({
				text,
				record
			}) => {
				return record.firstName + ' ' + record.lastName
			},
		},
		{
			title: $T('self.userCharge.tips4'),
			dataIndex: 'mobile',
			key: 'mobile'
		},
		{
			title: $T('self.userCharge.tips5'),
			dataIndex: 'money',
			key: 'money'
		},
		{
			title: $T('self.userCharge.tips7'),
			dataIndex: 'type',
			key: 'type'
		},
		{
			title: $T('self.userCharge.tips12'),
			dataIndex: 'agent',
			key: 'agent'
		},
		{
			title: $T('self.createTimeTxt'),
			dataIndex: 'dateTime',
			key: 'dateTime'
		},
	]
	const sourceTypeOptions = ref([])
	const getSourceTypeTxt = (status) => {
		if (status == null) return '--'
		const map = sourceTypeOptions.value.find(item => item.id === Number(status))
		return map?.label || '--'
	}
	const resetDefaultOptionsByLang = () => {
		// 来源
		// 2 后台财务卡片充值，
		// 3 app钱包充值,
		// 4 cash充值
		// 5 MTNMobileMoney充值
		// 6 MomoCode充值
		// 7 CreditCard充值
		// 8 AirtelMoney充值
		// 9 points 分享积分转金额
		sourceTypeOptions.value = [{
				label: $T('self.userCharge.sourceTypes.tips1'),
				id: 2
			},
			{
				label: $T('self.userCharge.sourceTypes.tips7'),
				id: 3
			},
			{
				label: $T('self.userCharge.sourceTypes.tips2'),
				id: 4
			},
			{
				label: $T('self.userCharge.sourceTypes.tips3'),
				id: 5
			},
			{
				label: $T('self.userCharge.sourceTypes.tips4'),
				id: 6
			},
			{
				label: $T('self.userCharge.sourceTypes.tips5'),
				id: 7
			},
			{
				label: $T('self.userCharge.sourceTypes.tips6'),
				id: 8
			},
			{
				label: $T('self.userCharge.sourceTypes.tips8'),
				id: 9
			},
		]

	}


	//历史充电记录
	const searchOrgOptionsHis = ref([])
	const searchStatusOptions = ref([])
	const onSearchFinishHis = (values) => {
		const params = {
			...values,
			orgId: values.orgId || '',
			orderNo: values.orderNo || '',
			mobile: values.mobile || '',
			stationId: values.stationId || '',
			status: values.status || '',
			userName: values.userName || '',
			gunType: values.gunType || '',
			vehicle: values.vehicle || '',
			startTime: values.startTime ? dayjs(values.startTime).format('YYYY-MM-DD HH:mm:ss') : '',
			endTime: values.endTime ? dayjs(values.endTime).format('YYYY-MM-DD HH:mm:ss') : '',
		};
		stableRefHis.value.upData(params, 1);
	};

	const resetSearchFormHis = () => {
		searchFormStateHis.value = {
			mobile: '',
			orderNo: '',
			orgId: null,
			stationId: '',
			startTime: '',
			endTime: '',
			status: 4,
			userName: '',
			vehicle: '',
			gunType: '',
		};
		stableRefHis.value.upData({}, 1);
	};
	const searchFormStateHis = ref({
		mobile: '',
		orderNo: '', 
		orgId: null, 
		stationId: '', 
		startTime: '', 
		endTime: '', 
		status: 4, 
		userName: '', 
		vehicle: '', 
		gunType: '', 
	})
	const vehicleTypeOptionsHis = ref([
		{ label: 'E-Car', value: 'car' },
		{ label: 'E-Motorcycle', value: 'moto' }
	]);
    const chargeTypeOptions = ref([
		{ label: 'DC', value: 2 },
		{ label: 'AC', value: 1 }
	]);
	const tableDataHis = ref([])
	const selectedKeyHis = ref([])
	const stableRefHis = ref(null)
	const searchOrderTypeOptions = ref([])
	// 表头用计算属性 切换中英文可立即切换回来
	const sourceColumnHis = computed(() => [
		{
		title: $T('self.order.tips210'),
		dataIndex: 'orderNo',
		key: 'orderNo'
		// width: 110
		},
		{
		title: $T('self.order.tips211'),
		dataIndex: 'userName',
		key: 'userName'
		},
		
		{
		title: $T('self.order.tips204'),
		dataIndex: 'mobile',
		key: 'mobile'
		},
		{
		title: $T('self.order.tips202'),
		dataIndex: 'cardNo',
		key: 'cardNo',
		width: 150
		},
		{
		title: $T('self.order.tips205'),
		dataIndex: 'createTime',
		key: 'createTime'
		},
		{
		title: $T('self.order.tips207'),
		dataIndex: 'stationName',
		key: 'stationName'
		},
		{
		title: $T('self.order.tips212'),
		dataIndex: 'stationId',
		key: 'stationId'
		},
		{
		title: $T('self.order.tips213'),
		dataIndex: 'gunNo',
		key: 'gunNo',
		customRender: ({text}) => {
			return (text == 1 ? "A":"B");
		},
		},
		{
		title: $T('self.businessStation.modal.col15'),
		dataIndex: 'vehicle',
		key: 'vehicle',
		customRender: ({text}) => {
			return (text == 1 ? "E-CARS":"MOTOS");
		},
		},
		{
		title: $T('self.order.tips208'),
		dataIndex: 'currentV',
		key: 'currentV'
		},
		{
		title: $T('self.order.tips209'),
		dataIndex: 'currentA',
		key: 'currentA'
		},
		{
		title: $T('self.order.tips203'),
		dataIndex: 'totalChargeQuantity',
		key: 'totalChargeQuantity',
		// 自定义显示列
		customRender: ({text, record}) => {
			// 将 text 转换为数值类型
			const numericValue = parseFloat(text);
			if (isNaN(numericValue)) return ''; // 如果不是有效的数值，则返回空字符串
			// 除以1000并保留最多2位小数
			return (numericValue / 1000).toFixed(2);
		},
		},
		{
		title: $T('self.order.tips214'),
		dataIndex: 'totalChargeTimes',
		key: 'totalChargeTimes',
		// 自定义显示列
		customRender: ({text, record}) => {
			// 接口返回是秒，处理为分
			return proxy.getMinBySeconds(text)
		},
		},
		{
		title: $T('self.order.tips215'),
		dataIndex: 'totalChargeMoney',
		key: 'totalChargeMoney'
		},
		// {
		// title: $T('self.order.tips216'),
		// dataIndex: 'totalServiceMoney',
		// key: 'totalServiceMoney'
		// },
		{
		title: $T('self.order.tips217'),
		dataIndex: '',
		key: ''
		},
		{
		title: $T('self.order.tips218'),
		dataIndex: '',
		key: ''
		},
		{
		title: $T('self.order.tips219'),
		dataIndex: 'closingReason',
		key: 'closingReason'
		},
	])

	searchOrderTypeOptions.value = [
		{
		label: $T('self.order.orderType.all'),
		value: ''
		},
		{
		label: $T('self.order.orderType.tips1'),
		value: 1
		},
		{
		label: $T('self.order.orderType.tips2'),
		value: 2
		},
		{
		label: $T('self.order.orderType.tips3'),
		value: 3
		},
		{
		label: $T('self.order.orderType.tips4'),
		value: 4
		},
		{
		label: $T('self.order.orderType.tips5'),
		value: 5
		}
	]


	const tableSelectionChangeHis = (rows, record) => {
		selectedKey.value = rows
	}
	// 表格API配置
	const totalRecords = ref(0);
	const apiObjHis = $API.backend.order.list;

	const paginationHis = reactive({
		current: 1,
		pageSize: 10,
		showSizeChanger: true,
		showQuickJumper: true,
		pageSizeOptions: ['10', '20', '50', '100', 'All'], 
		showTotal: total => `共 ${total} 条`,
		onShowSizeChange: (current, size) => {
				let finalSize = size;
				if (size === 'All') {
					finalSize = totalRecords.value;
				}

				paginationHis.current = 1;
				paginationHis.pageSize = finalSize;

				tableParams.pageNo = 1;
				tableParams.pageSize = finalSize;
				// nextTick(() => {
				// 	stableRefHis.value?.upData(tableParams, 1)
				// })
				stableRefHis.value.upData(tableParams, 1);
		},
		onChange: (page, pageSize) => {
			// 1. 更新本地分页状态
			paginationHis.current = page;
			paginationHis.pageSize = pageSize;

			// 2. 直接修改 tableParams 对象，触发响应式更新
			tableParams.pageNo = page;
			tableParams.pageSize = pageSize;

			// 3. 调用 upData 方法，让 s-table 重新请求数据
			// nextTick(() => {
			// 	stableRefHis.value?.upData(tableParams, 1)
			// })
			stableRefHis.value.upData(tableParams, 1);
		},
	})





	//地图相关
	const loader = new Loader({
		apiKey: 'AIzaSyCakn6sn2RFM9GKevATBEZjtTeGSiKFdwE',
		version: 'weekly',
		libraries: []
	})

	loader.load().then(() => {
		initGoogleMap()
	})

	const initGoogleMap = () => {
		map = new google.maps.Map(document.getElementById('google-map'), {
			zoom: 10,
			center: {
				lat: 39.9042,
				lng: 116.4074
			}
		})
		handleOrgChange()
	}

	const africaTestTypeOptions = computed(() => {
		const selectedCountry = mapSearchFormState.value.authorizedCountryCode;
		if (!selectedCountry) return []; 

		const cities = cityRaw[selectedCountry] || [];
		return cities.map(c => ({
			label: `${c.labelCn} / ${c.labelEn}` + (c.labelRW ? ` / ${c.labelRW}` : ''),
			value: `${selectedCountry}_${c.labelEn}`, 
			countryCode: selectedCountry,
			labelCn: c.labelCn,
			labelEn: c.labelEn,
			labelRW: c.labelRW
		}));
	});
	const handleAfricaCountryChange = async (countryCode) => {
		mapSearchFormState.value.authorizedCountryCode = countryCode;
		// mapSearchFormState.value.africaTestTypeName = null;
		const selectedCountry = africaCountryOptions.find(item => item.value === countryCode);
		mapSearchFormState.value.africaCountry = selectedCountry ? selectedCountry.labelEn : null;
	};
	const africaCountryOptions = cityData.africaCountryOptions.map(item => ({
		...item,
		display: `${item.labelCn} / ${item.labelEn}` + (item.labelRW ? ` / ${item.labelRW}` : '')
	}));
	const handleAfricaTestTypeChange = (testType) => {
		const selectedCity = africaTestTypeOptions.value.find(item => item.value === testType);
		mapSearchFormState.value.africaTestType = selectedCity ? selectedCity.labelEn : null;
	};

	// 3. 车辆类型选项 E-Motorcycle、E-Car
	const vehicleTypeOptions = ref([
		{ label: 'E-Car', value: 'E-Car' },
		{ label: 'E-Motorcycle', value: 'E-Motorcycle' }
	]);

	// 4. 充电桩容量选项120kw、70kw、7kw
	const pileCapacityOptions = ref([
		{ label: '120kW', value: '120' },
		{ label: '70kW', value: '70' },
		{ label: '7kW', value: '7' }
	]);

	// 5. 充电桩状态选项（充电中、空闲、故障）1 故障  3空闲 4充电中"
	const pileStatusOptions = ref([
		{ label: $T('self.businessCharging.states,tips5'), value: 4 },
		{ label: $T('self.businessCharging.states,tips4'), value: 3 },
		{ label: $T('self.businessCharging.states,tips2'), value: 1 }
	]);

	// 地图搜索表单Ref（用于重置/验证）
	const mapSearchFormRef = ref(null);

	// 地图搜索表单状态
	const mapSearchFormState = ref({
		africaCountry: null,    // 非洲国家编码
		africaCountryName: null, // 非洲国家名称
		authorizedCountryCode:null,
		africaTestType: null,   // 城市
		africaTestTypeName: null, // 城市名称
		vehicleType: null,      // 车辆类型
		pileCapacity: null,     // 充电桩容量
		pileStatus: null        // 充电桩状态
	});


	// 3. 车辆类型变更事件
	const handleVehicleTypeChange = (vehicleType) => {
		mapSearchFormState.value.vehicleType = vehicleType;
	};

	// 4. 充电桩容量变更事件
	const handlePileCapacityChange = (capacity) => {
		mapSearchFormState.value.pileCapacity = capacity;
	};

	// 5. 充电桩状态变更事件
	const handlePileStatusChange = (status) => {
		mapSearchFormState.value.pileStatus = status;
	};

	// 地图表单提交事件
	const onMapSearchFinish = async (values) => {
		// {{url}}/admin/getStationList      
		// {"supportingFacilities":"E-Motorcycle、E-Car",
		// "stationAreaDetail":"地区","stationArea":"国家",
		// "chargePilePowerMax":"功率：120",
		// "pileState":"状态：1 故障  3空闲 4充电中"}
		try {
			const submitParams = {
				orgId: formState.value.orgIds, 
				// stationId: formState.value.chargeStationIds, 
				stationArea: mapSearchFormState.value.africaCountryName, // 国家
				stationAreaDetail: mapSearchFormState.value.africaTestTypeName,// 地区
				supportingFacilities: mapSearchFormState.value.vehicleType,//"E-Motorcycle、E-Car",
				chargePilePowerMax: mapSearchFormState.value.pileCapacity,// 功率
				pileState: mapSearchFormState.value.pileStatus// 新增：充电桩状态
			};
			// console.log('>>> 地图搜索提交参数', submitParams);
			const res = await $API.backend.businessStation.getStationList.post(submitParams);
			if (res.code === 200) {
				// console.log('>>> 地图搜索结果', res.objData);
				stationOptions.value = res.objData ?? []
				renderStationMarkers(res.objData)
			}
		} catch (error) {
			message.error($T('self.message.searchFailed'));
		}
	};

	// 地图表单重置事件
	const resetMapSearchForm = () => {
		if (mapSearchFormRef.value) {
			mapSearchFormRef.value.resetFields();
			// 重置后刷新默认地图标记（如显示所有站点）
			renderStationMarkers(stationOptions.value);
		}
	};

	const firstDrawStation = async () => {
		try {
			// 增加超时控制，防止无限等待
			await Promise.race([
			loader.load(),
			new Promise((_, reject) => 
				setTimeout(() => reject(new Error('loader加载超时')), 10000)
			)
			]);
			console.log('loader加载完成');
			
			initGoogleMap()
			await nextTick()
			formState.value.orgIds = []
			await onMapSearchFinish({});
		} catch (error) {
			console.error('firstDrawStation内部错误:', error);
			throw error; 
		}
	}
	//站点地图
	const renderStationMarkers = (markerDataList) => {
		// console.log('>>> 进入 render 时的长度', markerDataList.length);

		for (const [index, data] of markerDataList.entries()) {
			try {
				const cleanLat = data.latitude?.replace(/[^\d.-]/g, '') ?? '';
				const cleanLng = data.longitude?.replace(/[^\d.-]/g, '') ?? '';

				const lat = parseFloat(cleanLat);
				const lng = parseFloat(cleanLng);

				if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
					console.warn(`>>> 第 ${index} 条坐标非法，跳过`, lat, lng);
					continue;
				}

				const marker = new google.maps.Marker({
					position: {
						lat,
						lng
					},
					title: `${data.stationName} - ${index}`,
					map,
				});

				const infoWindow = new google.maps.InfoWindow({
					content: `
						<div style="padding:6px;line-height:1.5;">
							<div><b>${data.stationName}</b></div>
							<div>地址：${data.stationAreaDetail || '--'}</div>
						</div>`,
				});

				marker.addListener('click', () => infoWindow.open(map, marker));
				markers.value.push(marker);
			} catch (err) {
				console.error(`>>> 第 ${index} 条处理失败`, err);
			}
		}

		// 自动居中
		if (markers.length) {
			const bounds = new google.maps.LatLngBounds();
			markers.forEach(m => bounds.extend(m.getPosition()));
			map.fitBounds(bounds);
		}
	};


	// 图表相关
	const chartRef = ref(null)
	const chartType = ref('totalCharge')
	let chartInstance = null
	const dateMode = ref('month')
	const dateMode1 = ref('year')
	const rangeValue = ref([]) //动态时间选择
	const chartRawList = ref([])
	// 把 dateMode 转成后端要的 type
	const typeMap = {
		day: 1,
		week: 2,
		month: 3,
		year: 4
	}
	const carMode = ref('moto')
	// 图表切换数据
	// type: 1日 2周 3月 4年
	const queryWeekSumWhere = async (type) => {
		console.log('queryWeekSumWhere', type,formState.value.endDate,formState.value.beginDate)
		try {
			const res = await $API.backend.index.WeekSumWhere.post({
				orgId: formState.value.orgIds,
				stationId: formState.value.chargeStationIds,
				beginDate: formState.value.beginDate,
				endDate: formState.value.endDate,
				type: type
			})
			if (res.code === 200) {
				chartRawList.value = res.objData || []
				updateChartByRaw()
			}
		} catch (e) {
			message.error($T('self.message.loadFailed'))
		}
	}
	//柱状图 点击钱包时 另外调用接口
	const querySumRfidCharge= async (type) => {
		try {
			const res = await $API.backend.index.querySumRfidCharge.post({
				orgId: formState.value.orgIds,
				stationId: formState.value.chargeStationIds,
				beginDate: formState.value.beginDate,
				endDate: formState.value.endDate,
				type: type
			})
			if (res.code === 200) {
				chartRawList.value = res.objData || []
				updateChartByRaw()
			}
		} catch (e) {
			message.error($T('self.message.loadFailed'))
		}
	}
	// 把 dateMode 映射成 a-range-picker 的 picker 属性
	const pickerType = computed(() => {
		const map = { year: 'year', month: 'month', week: 'week', day: 'date' }
		return map[dateMode.value]
	})
	// 动态时间区段选择占位符
	const rangePlaceholder = computed(() => {
		const map = {
			year:  [$T('self.stationMap.tips49'), $T('self.stationMap.tips50')], // Starting year / End of Year
			month: [$T('self.stationMap.tips51'), $T('self.stationMap.tips52')], // Starting Month / End Month
			week:  [$T('self.stationMap.tips53'), $T('self.stationMap.tips54')], // Starting Week / End of Week
			day:   [$T('self.stationMap.tips55'), $T('self.stationMap.tips56')]  // Starting date / End Date
		}
		return map[dateMode.value] || map.month
	})
	// 维度切换时清空区间
	watch(dateMode, () => { rangeValue.value = [] })

	// 区间变化 -> 格式化 -> 重新拉数据
	const onRangeChange = (dates) => {
		if (!dates || dates.length !== 2) return
		const [start, end] = dates
		let fmt = 'YYYY'
		if (dateMode.value === 'month') fmt = 'YYYY-MM'
		if (dateMode.value === 'week') fmt = 'YYYY-w' 
		if (dateMode.value === 'day' || dateMode.value === 'year') fmt = 'YYYY-MM-DD'
		formState.value.beginDate = start.format(fmt)
		formState.value.endDate = end.format(fmt)
		loadChartData()
	}
	const updateChartByRaw = () => {
		if (!chartInstance) initChart()
		if (!chartInstance) return
		const list = chartRawList.value

		const keyMap = {
			totalChargeCount: 'totalChargeCount',
			totalCharge: 'totalCharge',
			totalChargeMoney: 'totalChargeMoney',
			totalChargeTime: 'totalChargeTime',
			totalServeceMoney: 'totalServeceMoney',
			Wallet: 'Wallet'
		}

		const field = keyMap[chartType.value] || 'totalCharge'


		// 处理数据，确保显示7条
		// let processedList = [...list];
		
		// // 如果数据不足7条，补充空数据到7条
		// if (processedList.length < 7) {
		// 	const emptyItems = Array(7 - processedList.length).fill({});
		// 	processedList = [...processedList, ...emptyItems];
		// } 
		// // 如果数据超过7条，只取前7条
		// else if (processedList.length > 7) {
		// 	processedList = processedList.slice(0, 7);
		// }
		// // 从处理后的数据中提取日期和值
		// const dates = processedList.map(item => {
		// 	return item.dateTime || item.datetime || '';
		// });
		// const values = processedList.map(item => {
		// 	return item[field] ? Number(item[field]) : 0;
		// });



		const dates = list.map(item => item.dateTime || item.datetime)
		const values = list.map(item => Number(item[field]) || 0)

		const option = {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				}
			},
			grid: {
				left: '3%',
				right: '4%',
				bottom: '3%',
				containLabel: true
			},
			xAxis: {
				type: 'category',
				data: dates,
				axisTick: {
					alignWithLabel: true
				}
			},
			yAxis: {
				type: 'value'
			},
			series: [{
				name: $T(`self.stationMap.${chartType.value}`),
				type: 'bar',
				barWidth: '60%',
				data: values,
				itemStyle: {
					color: '#1890ff'
				}
			}]
		}
		chartInstance.setOption(option, true)
	}

	// const initChart = () => {
	// 	if (chartInstance) {
	// 		chartInstance.dispose()
	// 		chartInstance = null
	// 	}
	// 	if (!chartRef.value) return
	// 	//用于下载
	// 	chartInstance = echarts.init(chartRef.value, null, { renderer: 'svg' }); 
	// 	// chartInstance = echarts.init(chartRef.value)
	// 	if (chartRawList.value.length) {
	// 		updateChartByRaw()
	// 	}
	// }
	// 修改 initChart 函数，添加准确的渲染器检测
	const initChart = () => {
		if (chartInstance) {
			chartInstance.dispose();
			chartInstance = null;
		}
		if (!chartRef.value) return;

		try {
			// 获取容器的实际宽高
			const container = chartRef.value;
			const { width, height } = container.getBoundingClientRect();
			
			// 初始化图表，强制使用SVG渲染器
			chartInstance = echarts.init(container, null, {
				renderer: 'svg',  // 明确指定SVG渲染器
				useDirtyRect: false,
				width: width || 800,
				height: height || 400
			});

			// 直接从painter对象获取渲染器类型（根据打印结果优化）
			const zr = chartInstance.getZr();
			if (zr && zr.painter && zr.painter.type) {
			console.log('当前渲染器类型:', zr.painter.type);
			if (zr.painter.type !== 'svg') {
				message.warning('图表未使用SVG渲染器，SVG下载功能可能不可用');
			}
			} else {
				console.log('渲染器类型检测正常，但访问路径与预期不同');
			}

			if (chartRawList.value.length) {
				updateChartByRaw();
			}

		} catch (initErr) {
			console.error('图表初始化失败：', initErr);
			message.error('图表加载失败，无法使用下载功能');
		}
	};

	// 修改 downloadSVG 函数，确保正确检测SVG渲染器
	const downloadSVG = () => {
		if (!chartInstance) {
			message.error('图表实例未初始化');
			return;
		}

		try {
			if (chartRawList.value.length === 0) {
				message.warning('图表无数据，无法生成 SVG');
				return;
			}

			// 从zr.painter.type检测渲染器类型（根据打印结果优化）
			const zr = chartInstance.getZr();
			if (!zr || !zr.painter || zr.painter.type !== 'svg') {
				message.error('当前图表不支持SVG导出，渲染器类型不符');
				console.error('渲染器类型错误:', zr?.painter?.type);
				return;
			}

			message.info('正在生成 SVG 文件，请稍候...');
			
			// 生成SVG并指定必要参数
			const svgString = chartInstance.toSVG({
				dpi: 150,
				backgroundColor: '#ffffff',
				width: 1200,
				height: 600
			});
			console.log("svgString",svgString)
			if (!svgString || svgString.trim() === '') {
				message.error('生成的 SVG 内容为空');
				return;
			}

			// 清理可能的非法属性
			const cleanedSvg = svgString
			.replace(/width="auto"/g, 'width="100%"')
			.replace(/height="auto"/g, 'height="100%"');

			const chartTitle = getChartTitle().replace(/[^\w\s-]/g, '');
			downloadFile(cleanedSvg, chartTitle, 'image/svg+xml', 'svg');
			message.success('SVG 下载成功');

		} catch (svgErr) {
			console.error('SVG 下载失败：', svgErr);
			message.error('下载 SVG 时发生错误');
		}
	};


	const loadChartData = () => {
		const type = typeMap[dateMode.value] ?? 3
		return queryWeekSumWhere(type)
	}

	// 更新图表
	const updateChart = (data) => {
		const option = {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				}
			},
			grid: {
				left: '3%',
				right: '4%',
				bottom: '3%',
				containLabel: true
			},
			xAxis: {
				type: 'category',
				data: data.dates || [],
				axisTick: {
					alignWithLabel: true
				}
			},
			yAxis: {
				type: 'value'
			},
			series: [{
				name: $T(`self.stationMap.${chartType.value}`),
				type: 'bar',
				barWidth: '60%',
				data: data.values || [],
				itemStyle: {
					color: '#1890ff'
				}
			}]
		}
		chartInstance.setOption(option)
	}

	// 图表类型切换 收入来源统计
	const handleChartTypeChange = ((type) => {
		if(type==1){//电量之类下面的年月日时间切换 1
			queryWeekSumWhere(typeMap[dateMode.value])		
		} else {//收入来源切换 3
			querySum(typeMap[dateMode1.value])		
		}
	})

	const handleChartTypeChangeZ = ((values) => {
		console.log('handleChartTypeChangeZ===', values.target.value)
		const type = values.target.value
		switch(type) {
			case 'totalCharge':
				queryWeekSumWhere(typeMap[dateMode.value])	
			break;
			case 'totalChargeMoney':
				queryWeekSumWhere(typeMap[dateMode.value])	
			break;
			case 'totalChargeCount':
				queryWeekSumWhere(typeMap[dateMode.value])	
			break;
			case 'totalChargeTime':
				queryWeekSumWhere(typeMap[dateMode.value])	
			break;
			case 'totalServeceMoney':
				queryWeekSumWhere(typeMap[dateMode.value])	
			break;
			case 'Wallet':
				querySumRfidCharge(typeMap[dateMode.value])	
			break;
		default:
			break;
		}
	})


	// 监听语言变化 日期维度切换
	watch(
		[() => mainStoreInstance.lang, dateMode],
		() => chartRef.value,
		() => {
			if (chartRef.value && !chartInstance) {
				initChart()
			}
		},
		([newLang, newMode], [oldLang, oldMode]) => {
			const type = typeMap[dateMode.value] ?? 3
			queryWeekSumWhere(type)
			if (newLang !== oldLang) {
				resetDefaultOptionsByLang()
				// resetDefaultOptionsByLangHis()
			}
		}, {
			immediate: true
		}
	)
	const loadData = () => {
		getUserOrgRole();
		resetDefaultOptionsByLang()
		querySum()
		// allAddUser()
		queryChargeGunCount()
		queryChargePileCount()
		queryAllStationCount()
		queryWeekSumWhere(3)
		queryPieData()
		AddUserOrg()
		updatePie1()
		updatePie2()
	}
	onUnmounted(() => {
		if (chartInstance) { chartInstance.dispose(); chartInstance = null }
		if (pieInstance)   { pieInstance.dispose();   pieInstance = null   }
		if (pieInstance1)   { pieInstance1.dispose();   pieInstance1 = null   }
		if (pieInstance2)   { pieInstance2.dispose();   pieInstance2 = null   }
		if (pieInstance3)   { pieInstance3.dispose();   pieInstance3 = null   }
		if (pieInstance4)   { pieInstance4.dispose();   pieInstance4 = null   }
	})

	const handleOrgChange = async (orgId) => {
		searchFormState.stationId = null
		stationOptions.value = []
		if (!orgId) {
			formState.value.orgIds = []
			return
		}
		formState.value.orgIds = [orgId]
		await queryStationAndRender(orgId)
	}
	//根据运营商获取该运营商的站点
	const queryStationAndRender = async (orgId) => {
		try {
			const res = await $API.backend.businessStation.queryStationListByOrgIds.post({
				orgIds: orgId || ''
			})
			if (res.code === 200) {
				stationOptions.value = res.objData ?? []
				// renderStationMarkers(res.objData)
			}
		} catch (e) {
			message.error($T('self.message.loadFailed'))
		}
	}


	// bingzhuang
	const pieRef = ref(null)              // 饼图 DOM
	const pieRef1 = ref(null)  
	const pieRef2 = ref(null)  
	const pieRef3 = ref(null)  
	const pieRef4 = ref(null)  
	let pieInstance = null                // 饼图实例
	let pieInstance1 = null 
	let pieInstance2 = null 
	let pieInstance3 = null 
	let pieInstance4 = null 
	/* 后端返回的一周各时段电量*/
	const pieRaw = ref({
		spike: 0,   // 尖
		peak: 0,    // 峰
		flat: 0,    // 平
		valley: 0   // 谷
	})

	const queryPieData = async () => {
		try {
			$API.backend.index.querySumTimeKwh.post({
				orgId: formState.value.orgIds,
				stationId: formState.value.chargeStationIds,
				type: 1
			}).then(res => {
				if(res.code == 200){
					summaryData.sumTimeKwh.avg = res.objData.avg || 0//累计平谷
					summaryData.sumTimeKwh.max = res.objData.max || 0//累计尖峰
					summaryData.sumTimeKwh.aslow = res.objData.aslow || 0//累计低谷
					summaryData.sumTimeKwh.height = res.objData.height || 0//累计高峰
					

					summaryData.sumTimeKwh.avgMoto = res.objData.avgMoto
					summaryData.sumTimeKwh.maxMoto = res.objData.maxMoto
					summaryData.sumTimeKwh.highYMoto = res.objData.highYMoto
					summaryData.sumTimeKwh.aslowMoto = res.objData.aslowMoto
					summaryData.sumTimeKwh.heightMoto = res.objData.heightMoto

					summaryData.sumTimeKwh.avgCar = res.objData.avgCar
					summaryData.sumTimeKwh.maxCar = res.objData.maxCar
					summaryData.sumTimeKwh.aslowCar = res.objData.aslowCar
					summaryData.sumTimeKwh.heightCar = res.objData.heightCar


					// maxY//尖峰
					// lowY//低谷
					// avgY//平谷
					// highY//高峰
					
					pieRaw.value = {
						spike: Number(res.objData.max || 0),
						peak:  Number(res.objData.height  || 0),
						flat:  Number(res.objData.avg  || 0),
						valley:Number(res.objData.aslow|| 0)
					}
				} else {
					pieRaw.value = {
						spike: 0,
						peak: 0,
						flat: 0,
						valley: 0
					}
				}
				updatePie()
			}).catch(err => {
				console.log(err)
				pieRaw.value = {
					spike: 0,
					peak: 0,
					flat: 0,
					valley: 0
				};
				updatePie();
			})
			
		} catch (e) {
				pieRaw.value = {
					spike: 0,
					peak: 0,
					flat: 0,
					valley: 0
				};
				updatePie();
			message.error($T('self.message.loadFailed'))
		}
	}

	/* 渲染饼图 */
	const updatePie = () => {
		if (!pieInstance) initPie(0)
		console.log("pieRaw.value----------------", pieRaw.value)
		const basePadding = Math.max(10, 60 - 4 * 10); // 10-60px 动态范围
		
		const option = {
			tooltip: {
				trigger: 'item',
				formatter: '{a} <br/>{b}: {c} ({d}%)'
			},
			legend: {
				show: true
			},
			series: [
				{
				name: $T('self.stationMap.tips27'),
				type: 'pie',
				radius: ['40%', '70%'],
				center: ['50%', '50%'],
				label: {
					show: true,
					position: 'outside',
					formatter: (params) => {
						return `{name|${params.name}}\n{value|${params.value} (${params.percent}%)}`;
					},
					rich: {
						name: {
							align: 'center',
							verticalAlign: 'middle',
							padding: [basePadding, 0, 0, 0], // 动态顶部内边距
							fontSize: 12,
							color: '#333'
						},
						value: {
							align: 'center',
							verticalAlign: 'middle',
							padding: [5, 0, 0, 0], // 固定小间距
							fontSize: 11,
							color: '#666'
						}
					}
				},
				labelLine: {
					show: true,
					length: 5,
					length2: 10
				},
				data: [
					{ value: pieRaw.value.spike || 0, name: $T('self.order.tips61') },
					{ value: pieRaw.value.peak || 0,  name: $T('self.order.tips62') },
					{ value: pieRaw.value.flat || 0,  name: $T('self.order.tips63') },
					{ value: pieRaw.value.valley || 0,name: $T('self.order.tips64') }
				]
				}
			]
		};
		pieInstance.setOption(option, true)
	}

	/* 初始化饼图实例 */
	const initPie = (type) => {
		if(type == 0){
			if (pieInstance) { pieInstance.dispose(); pieInstance = null }
			pieInstance = echarts.init(pieRef.value)
		} else if(type == 1){
			if (pieInstance1) { pieInstance1.dispose(); pieInstance1 = null }
			pieInstance1 = echarts.init(pieRef1.value)
		} else if(type == 2){
			if (pieInstance2) { pieInstance2.dispose(); pieInstance2 = null }
			pieInstance2 = echarts.init(pieRef2.value)
		} else if(type == 3){
			if (pieInstance3) { pieInstance3.dispose(); pieInstance3 = null }
			pieInstance3 = echarts.init(pieRef3.value)
		} else {
			if (pieInstance4) { pieInstance4.dispose(); pieInstance4 = null }
			pieInstance4 = echarts.init(pieRef4.value)
		}
	}
	const updatePie1 = () => {
		if (!pieInstance1) initPie(1)
		const option = {
			tooltip: {
			trigger: 'item',
			formatter: '{a} <br/>{b}: {c} ({d}%)'
			},
			legend: {
			show: true
			},
			series: [
			{
				name: $T('self.stationMap.tips27'),
				type: 'pie',
				radius: ['40%', '70%'],
				center: ['50%', '50%'],
				label: {
				show: true,
				position: 'outside',
				formatter: (params) => {
					if (params.name.includes('E-Motorcycle')) {
					return '{a|E-Motorcycle}\n{b|' + params.value + ' (' + params.percent + '%)}';
					} else {
					// 这里需要补充 `c` 和 `d` 类的样式引用
					return '{c|E-Car}\n{d|' + params.value + ' (' + params.percent + '%)}';
					}
				},
				rich: {
					a: {
					align: 'center',
					verticalAlign: 'bottom',
					padding: [0, 0, 20, 0], // E-Motorcycle 底部内边距（保持原有）
					fontSize: 12,
					color: '#333'
					},
					b: {
					align: 'center',
					verticalAlign: 'bottom',
					padding: [-15, 0, 0, 0], // E-Motorcycle 数字内边距（保持原有）
					fontSize: 12,
					color: '#666'
					},
					// 新增 E-Car 标签的样式类 `c`
					c: {
					align: 'center',
					verticalAlign: 'top', // 垂直对齐方式改为顶部
					padding: [20, 0, 0, 0], // 顶部内边距增加到 20px
					fontSize: 12,
					color: '#333'
					},
					// 新增 E-Car 数字的样式类 `d`
					d: {
					align: 'center',
					verticalAlign: 'top', // 垂直对齐方式改为顶部
					padding: [8, 0, 0, 0], // 底部内边距调整（负数值向上推）
					fontSize: 12,
					color: '#666'
					}
				}
				},
				labelLine: {
				show: true,
				length: 5,
				length2: 10
				},
				data: [
				{ value: summaryData.EMotorcycle, name: $T('self.businessStation.vehicleType.tips1') },
				{ value: summaryData.ECar,  name: $T('self.businessStation.vehicleType.tips2') }
				]
			}
			]
		};
		pieInstance1.setOption(option, true)
	}
	const updatePie2 = () => {
		if (!pieInstance2) initPie(2);
		const color = ['#5470c6', '#91cc75'];
		const pieData = [
			{ 
			value: summaryData.pileInfo.motoCharging, 
			name: $T('self.businessStation.vehicleType.tips1'), 
			itemStyle: { color: color[0] } 
			},
			{ 
			value: summaryData.pileInfo.carCharging, 
			name: $T('self.businessStation.vehicleType.tips2'), 
			itemStyle: { color: color[1] } 
			}
		];
		// const total = pieData.reduce((sum, item) => sum + item.value, 0);
		// const basePadding = Math.max(10, 60 - pieData.length * 10);
		const option = {
			color,
			tooltip: { 
			trigger: 'item', 
			formatter: '{a} <br/>{b}: {c} ({d}%)' 
			},
			legend: { 
			show: true,
			top: 'top',
			left: 'center'
			},
			series: [
			{
				name: $T('self.stationMap.tips31'),
				type: 'pie',
				radius: ['40%', '70%'], 
				center: ['50%', '50%'],
				label: {
				show: true,
				position: 'outside', 
				formatter: (params) => {
					return `{name|${params.name}}\n{value|${params.value} (${params.percent.toFixed(1)}%)}`;
				},
				rich: {
					name: {
					align: 'center',
					verticalAlign: 'middle',
					padding: [5, 0, 0, 0], 
					fontSize: 12,
					color: '#333'
					},
					value: {
					align: 'center',
					verticalAlign: 'middle',
					padding: [5, 0, 0, 0],
					fontSize: 11,
					color: '#666'
					}
				}
				},
				labelLine: {
				show: true,
				length: 5,
				length2: 10 
				},
				data: pieData
			}
			]
		};
		
		pieInstance2.setOption(option, true);
	};
	const updatePie3 = () => {
  		if (!pieInstance3) initPie(3)
  
		// 处理空地区名称的情况
		const formattedData = summaryData.areaData.map(item => ({
			value: item.num,
			name: item.area || $T('self.stationMap.unknownArea')
		}));
		
		// 获取数据数量，用于动态调整样式
		const dataCount = formattedData.length;
		
		// 根据数据数量计算基础间距（条目越多，间距越小）
		const basePadding = Math.max(10, 60 - dataCount * 10); // 10-60px 动态范围
		
			const option = {
			tooltip: {
				trigger: 'item',
				formatter: '{a} <br/>{b}: {c} ({d}%)'
			},
			legend: {
				show: true
			},
			series: [
				{
				name: $T('self.stationMap.tips27'),
				type: 'pie',
				radius: ['40%', '70%'],
				center: ['50%', '50%'],
				label: {
					show: true,
					position: 'outside',
					// 通用格式化器，适用于所有条目
					formatter: (params) => {
					// 使用统一的样式类，避免按名称判断
					return `{name|${params.name}}\n{value|${params.value} (${params.percent}%)}`;
					},
					rich: {
						name: {
							align: 'center',
							verticalAlign: 'middle',
							padding: [basePadding, 0, 0, 0], // 动态顶部内边距
							fontSize: 12,
							color: '#333'
						},
						value: {
							align: 'center',
							verticalAlign: 'middle',
							padding: [5, 0, 0, 0], // 固定小间距
							fontSize: 11,
							color: '#666'
						}
					}
				},
				// 标签线长度也根据数据量动态调整
				labelLine: {
					show: true,
					length: Math.max(5, 20 - dataCount * 3), // 5-20px 动态范围
					length2: Math.max(10, 30 - dataCount * 4) // 10-30px 动态范围
				},
				data: formattedData
				}
			]
			};

	pieInstance3.setOption(option, true)
	}
	const updatePie4 = () => {
		if (!pieInstance4) initPie(4);
		const color = ['#5470c6', '#91cc75'];
		
		const pieData = [
			{ 
				value: summaryData.motoMoney || 0,
				name: $T('self.businessStation.vehicleType.tips1'),
				itemStyle: { color: color[0] } 
			},
			{ 
				value: summaryData.carMoney || 0, 
				name: $T('self.businessStation.vehicleType.tips2'), 
				itemStyle: { color: color[1] } 
			}
		];
		
		const dataCount = pieData.length;
		const basePadding = Math.max(10, 60 - dataCount * 10);
		
		const option = {
				color,
				tooltip: { 
				trigger: 'item', 
				formatter: '{a} <br/>{b}: {c} ({d}%)' 
			},
			legend: { 
				show: true,
				top: 'top',
				left: 'center'
			},
			series: [
			{
				name: $T('self.stationMap.tips31'),
				type: 'pie',
				radius: ['40%', '70%'],
				center: ['50%', '50%'],
				label: {
				show: true,
				position: 'outside',
				formatter: (params) => {
					return `{name|${params.name}}\n{value|${params.value} (${params.percent.toFixed(1)}%)}`;
				},
				rich: {
					name: {
					align: 'center',
					verticalAlign: 'middle',
					padding: [5, 0, 0, 0],
					fontSize: 12,
					color: '#333'
					},
					value: {
					align: 'center',
					verticalAlign: 'middle',
					padding: [5, 0, 0, 0],
					fontSize: 11,
					color: '#666'
					}
				}
				},
				labelLine: {
				show: true,
				length: 5,
				length2: 10 
				},
				data: pieData
			}
			]
		};
		
		pieInstance4.setOption(option, true);
	};




	//下载相关
	const handleDownload = (e) => {
		const type = e.key; // 'print', 'svg', 'pdf', 'excel', 'csv', 'jpeg'

		switch (type) {
			case 'print':
				printChart();
				break;
			case 'svg':
				downloadSVG();
				break;
			case 'pdf':
				downloadPDF();
				break;
			case 'excel':
				downloadExcel();
				break;
			case 'csv':
				downloadCSV();
				break;
			case 'jpeg':
				downloadJPEG();
				break;
			default:
				message.info(`Download ${type} is not implemented yet.`);
		}
	};

	/**
	 * 获取当前图表的标题，用于文件名
	 */
	const getChartTitle = () => {
		const periodMap = {
			'day': 'Day',
			'week': 'Week',
			'month': 'Month',
			'year': 'Year'
		};
		const metricMap = {
			'totalCharge': $T('self.stationMap.tips14')+(Kwh),
			'totalChargeMoney': $T('self.stationMap.tips1')+(RWF),
			'totalChargeCount': $T('self.stationMap.tips2')+(RWF),
			'totalChargeTime': $T('self.stationMap.tips15')+(HOURS),
			'totalServeceMoney': $T('self.stationMap.tips47')+(RWF),
			'Wallet': $T('self.stationMap.tips48')+(RWF)
		};
		return `${periodMap[dateMode.value]}ly ${metricMap[chartType.value]}`;
	};

	/**
	 * 打印图表
	 */

	const printChart = () => {
		if (!chartInstance) return;

		// 1. 强制 ECharts 立即渲染，确保获取到最新的 SVG
		// 这一步至关重要，它会刷新图表的 DOM 元素
		chartInstance.setOption(chartInstance.getOption());

		// 2. 获取图表的 DOM 元素的 HTML
		const chartHtml = chartInstance.getDom().innerHTML;
		const title = getChartTitle();

		const printWindow = window.open('', '_blank');
		printWindow.document.write(`
			<html>
				<head>
					<title>Print ${title}</title>
					<style> 
						body { margin: 20px; font-family: sans-serif; }
						h1 { text-align: center; color: #333; }
						.chart-container { border: 1px solid #eee; padding: 10px; }
					</style>
				</head>
				<body>
					<h1>${title}</h1>
					<div class="chart-container">${chartHtml}</div>
				</body>
			</html>
		`);
		printWindow.document.close(); // 关闭 document 的写入流，触发 DOMContentLoaded

		// 3. 等待新窗口的资源加载完成后再打印
		// 使用 setTimeout 是最简单可靠的方法
		setTimeout(() => {
			printWindow.print();
			// 可选：打印后自动关闭窗口
			// printWindow.close(); 
		}, 500); // 500ms 的延迟通常足够
	};
	/**
	 * 下载 SVG (适配不同渲染器)
	 */

	// const downloadSVG = () => {
	// 	if (!chartInstance) {
	// 		message.error('Chart instance is not initialized.');
	// 		return;
	// 	}

	// 	try {
	// 		// 1. 获取图表的 SVG 字符串
	// 		// 这是最关键的一步，它直接向 ECharts 实例请求 SVG 数据。
	// 		const svgString = chartInstance.getOption().toSVG();

	// 		if (svgString) {
	// 			// 2. 使用通用的 downloadFile 函数下载
	// 			downloadFile(svgString, getChartTitle(), 'image/svg+xml', 'svg');
	// 		} else {
	// 			// 如果获取失败，给出明确提示
	// 			message.error('Failed to generate SVG from the chart.');
	// 		}
	// 	} catch (error) {
	// 		// 捕获任何可能发生的异常
	// 		console.error('Error during SVG download:', error);
	// 		message.error('An error occurred while downloading the SVG.');
	// 	}
	// };

	/**
	 * 下载 PDF (此功能需要额外库，这里提供一个基于 window.print 的变通方案)
	 */
	const downloadPDF = () => {
		message.info('PDF download is initiated via the print dialog. Please select "Save as PDF" in your printer options.');
		printChart();
		// 注意：要实现真正的 PDF 导出，建议使用 jsPDF 或 html2pdf.js 等库，
		// 需要将 ECharts 的 SVG/Canvas 转换为图片再插入 PDF。
	};


	/**
	 * 下载 JPEG
	 */
	const downloadJPEG = () => {
		if (!chartInstance) return;
		// 获取图表的 Base64 图片数据
		const dataURL = chartInstance.getDataURL({
			type: 'jpeg',
			pixelRatio: 2, // 提高分辨率
			backgroundColor: '#fff'
		});
		downloadBase64File(dataURL, getChartTitle(), 'image/jpeg', 'jpg');
	};

	/**
	 * 下载 Excel
	 */
	const downloadExcel = () => {
		if (!chartRawList.value.length) return message.warning('No data to download.');
		
		// 准备要导出的数据
		const exportData = chartRawList.value.map(item => {
			const field = chartType.value;
			const value = Number(item[field]) || 0;
			return {
				'Period': item.dateTime || item.datetime,
				[getChartTitle()]: value
			};
		});

		// 使用 XLSX 库创建工作簿和工作表
		const ws = XLSX.utils.json_to_sheet(exportData);
		const wb = XLSX.utils.book_new();
		XLSX.utils.book_append_sheet(wb, ws, "Data");
		
		// 触发下载
		XLSX.writeFile(wb, `${getChartTitle()}.xlsx`);
	};

	/**
	 * 下载 CSV
	 */
	const downloadCSV = () => {
		if (!chartRawList.value.length) return message.warning('No data to download.');
		
		// 准备 CSV 内容
		const headers = ['Period', getChartTitle()];
		const rows = chartRawList.value.map(item => {
			const field = chartType.value;
			const value = Number(item[field]) || 0;
			return [item.dateTime || item.datetime, value];
		});
		
		// 将数据转换为 CSV 字符串
		const csvContent = [
			headers.join(','),
			...rows.map(row => row.join(','))
		].join('\n');
		
		downloadFile(csvContent, getChartTitle(), 'text/csv', 'csv');
	};


	/**
	 * 通用文件下载函数
	 * @param {string} content - 文件内容
	 * @param {string} baseFileName - 基础文件名
	 * @param {string} mimeType - MIME类型
	 * @param {string} extension - 文件扩展名
	 */
	const downloadFile = (content, baseFileName, mimeType, extension) => {
		const blob = new Blob([content], { type: mimeType });
		const url = URL.createObjectURL(blob);
		const a = document.createElement('a');
		a.href = url;
		a.download = `${baseFileName.replace(/\s+/g, '_')}.${extension}`;
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
		URL.revokeObjectURL(url);
	};

	/**
	 * 从 Base64 数据 URL 下载文件
	 */
	const downloadBase64File = (dataURL, baseFileName, mimeType, extension) => {
		const a = document.createElement('a');
		a.href = dataURL;
		a.download = `${baseFileName.replace(/\s+/g, '_')}.${extension}`;
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
	};
	const handleJumpToDetail = (type,id) => {
		const userInfo = userStoreInstance.provider || {};
		console.log("当前用户信息：", userInfo); 
		console.log("当前用户角色（userInfo.role）：", userInfo.role);

		// 2. 获取用户权限列表（permission.js 中用 userInfo.role 作为权限，这里直接复用）
		// 注意：permission.js 里 data.user.permissionList = userInfo.role，所以权限列表就是 userInfo.role
		const userRoles = userInfo.role || []; 

		// 3. 权限校验（完全对齐 permission.js 逻辑：判断角色是否在允许范围内）
		// permission.js 中路由权限基于 userInfo.role，这里同样用它判断
		const hasPermission = userRoles.some(role => ['user', id].includes(role));
		console.log("权限检查结果（与路由拦截逻辑一致）：", hasPermission, "用户权限：", userRoles);

		if (hasPermission) {
			 switch (type) {
				case 1:
					router.push({
						path: '/report/TotalChargingReport'
					});
					break;
				case 2:
					router.push({
						path: '/business/operators'
					});
					break;
				case 3:
					router.push({
						path: '/user/charge'
					});
					break;
				case 4:
					router.push({
						path: '/order/charging'
					});
					break;
				case 5://不能到详情 需要站id
					router.push({
						path: '/business/station'
					});
					break;
				case 6:
					router.push({
						path: '/user/list'
					});
					break;
				case 7:
					router.push({
						path: '/user/agents'
					});
					break;
				default:
					break;
			}
		} else {
			message.warning(proxy.$t('self.stationMap.message.msg1'));
		}
	};
	onMounted(() => {
		initChart()
		loadData();
		(async () => {
			try {
				await firstDrawStation();
				console.log("firstDrawStation 执行完成");
				// stableRefHis.value.upData(tableParams, 1);
			} catch (error) {
				console.error("firstDrawStation 执行失败:", error);
			}
		})();
	})
</script>

<style lang="scss" scoped>
	.jump-to-detail {
		cursor: pointer;
	}
	.jump-to-detail .data-label:last-child {
		color: #1890ff; 
		/* text-decoration: underline;  */
	}
	.jump-to-detail:hover .data-label:last-child {
		color: #096dd9;
	}
	::v-deep .ant-card-body {
		padding: 10px;
	}
	.station-map-container {
		padding:0 16px 16px 16px;
		min-height: 100vh;
	}

	.data-summary-section {
		margin-bottom: 16px;
	}

	.summary-card {
		height: 200px;
		border-radius: 5px;
		.card-title {
			font-size: 17px;
			font-weight: 700;
			color: #DAE5EA;
		}

		.card-content {
			.data-item {
				display: flex;
				justify-content: space-between;
				border-radius: 5px;
				&:last-child {
					margin-bottom: 0;
				}

				.data-label {
					color: #ededed;
					font-size: 16px;
				}

				.data-value {
					color: #fff;
					font-size: 18px;
					font-weight: 600;

					&.large {
						font-size: 32px;
						text-align: center;
						display: block;
						margin-top: 20px;
					}
				}
			}
		}
	}

	.bg1{
		background-color: #206463;
	}
	.bg2{
		background-color: #193DC9;
	}
	.bg3{
		background-color: #DB9444;
	}
	.bg4{
		background-color: #4C4D48;
	}
	.bg5{
		background-color: #BD3039;
	}
	.bg6{
		background-color: #1F812A;
	}
	.bg7{
		background-color: #CD2887;
	}
	.bg8{
		background-color: #782829;
	}
	.bg9{
		background-color: #4205BF;
	}
	.bg10{
		background-color: #EB6D44;
	}
	.bg11{
		background-color: #2A6859;
	}
	.bg12{
		background-color: #B79B6C;
	}
	.bg13{
		background-color: #DE3D35;
	}
	.bg14{
		background-color: #313E2B;
	}
	.bg15{
		background-color: #0e20e3;
	}
	.bg16{
		background-color: #bd0564;
	}
	.bg17{
		background-color: #0b209b;
	}
	.bg18{
		background-color: #118a88;
	}
	.bg19{
		background-color: #C15937;
	}
	.bg20{
		background-color: #5F7007;
	}
	.map-section {
		margin-bottom: 16px;

		.google-map-container {
			width: 100%;
			height: 500px;
			background: #e0e0e0;
		}
	}
	/* 横向滚动容器 */
	.indicator-scroll-wrapper {
		width: 100%;
		overflow-x: auto;
		white-space: nowrap;
		overflow-y: hidden;
	}

	.indicator-radio-group {
		display: inline-flex !important;
		gap: 8px;
	}
	.indicator-radio-group .ant-radio-button-wrapper {
		height: 40px;
		line-height: 40px;
	}
	.chart-section {
		.chart-container {
			padding: 20px 0;
		}
	}

	:deep(.station-info-window) {
		padding: 10px;

		h4 {
			margin: 0 0 10px 0;
			color: #333;
		}

		p {
			margin: 5px 0;
			color: #666;
		}
	}
	:deep(.chart-download-dropdown) {
		min-width: 160px;
		.ant-menu-item {
			display: flex;
			align-items: center;
			gap: 8px;
		}
	}
	:deep(.ant-row-middle){
		display: flex;
		flex-flow: row nowrap;
		justify-content: space-between;
	}
	
	.bnt{ 
		width: 80px;
		height: 30px;
		line-height: 30px;
		padding: 2px 5px;
		color: #27b32e;
		border-radius: 4px;
		align-items: center;
		justify-content: center;
		display: flex;
		border: 1px solid #27b32e;
	}
	:deep(.ant-dropdown-menu) {
		margin-top: 10px;
		width: 200px;
		height: auto;
		line-height: 30px;
		padding: 5px;
		color: #333;
		border-radius: 4px;
		display: flex;
		flex-direction: column;
	}
	.chart-row {
	display: flex;
	align-items: center; 
	margin-top: 20px;
	margin-bottom: 20px;
	}

	.pie-col {
	display: flex;
	justify-content: center; 
	align-items: center;
	}

	.pie-card {
	width: 100%;
	max-width: 550px;
	height: 472px; 
	display: flex;
	flex-direction: column;
	justify-content: center;
	}

	.pie-container {
	width: 100%;
	height: calc(100% - 40px);
	margin: 0 auto;
	}


	@media (max-width: 767px) {
	.pie-card {
		max-width: 100%;
		height: auto;
		padding: 16px;
	}
	.pie-container {
		height: 350px;
	}
	}
</style>